#include <math.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>

#include "Constant.h"
#include "NeighborDiscover.h"

int sockfd;
int recvCounter[256];
float neighbourRR[256];

char recvRouter[MAX_PACKET_LEN];
int recvLen;
pthread_mutex_t recv_mutex;

pthread_t p_id;
pthread_attr_t p_attr;

void cul_linkQuality();

void recv_init()
{
	printf("recv_init\n");
	if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 )
	{
		perror("Recv_init---socket.");
		printf("errno:%d\n", errno);
		exit(1);
	}

	int so_broadcast = 1;
	setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &so_broadcast, sizeof(so_broadcast));

	struct sockaddr_in broadcast_addr;
	bzero(&broadcast_addr, sizeof(broadcast_addr));
	broadcast_addr.sin_family = AF_INET;
	broadcast_addr.sin_port = htons(BROADCASTPORT);
	if(inet_aton(BROADCASTIP, &broadcast_addr.sin_addr) < 0 )
	{
		perror("Recv_init---inet_aton.");
		printf("errno:%d\n", errno);
		exit(1);
	}
	
	if(bind(sockfd,(struct sockaddr*)&broadcast_addr,sizeof(broadcast_addr)) < 0)
	{
		perror("Recv_init---bind.");
		printf("errno:%d\n", errno);
		exit(1);
	}

	pthread_mutex_init(&recv_mutex, NULL);
}

void *recv_departure(void *null)
{
	printf("recv_departure\n");
	char tmp[200];
	char packet[MAX_PACKET_LEN];
	int len;
	struct sockaddr_in addr;
	size_t addrlen;
	bzero(tmp, sizeof(tmp));
	while(1)
	{
		if((len=recvfrom(sockfd, packet, MAX_PACKET_LEN, 0, (struct sockaddr *)&addr, &addrlen)) < 0)
		{
			perror("recv---recvfrom.");
			printf("errno:%d\n",errno);
		}
		else
		{
			strcpy(tmp, inet_ntoa(addr.sin_addr));
			if(strcmp(HOSTIP,tmp) != 0 && packet[0] == 0x01)
			{
				//filter out the broadcast packets from itself.
				updateTable(packet+1, len-1);
			}
		}
	}
	return (void*)NULL;
}
